import React, { PropsWithChildren } from 'react';
import { Form, message } from 'antd';
import {
  ModalForm,
  ProFormText, ProFormTextArea,
} from '@ant-design/pro-components';
import { brandV1AdminControllerUpdate, brandV1AdminControllerCreate } from '@/services/auto/brandAdmin';
import FileUpload from "@/components/FileUpload";
import { FileGroup } from "common/utils/data";

interface FormData extends Omit<API.BrandAdminCreateDto, 'img'> {
  imgs: string[];
}

interface Props {
  data?: API.BrandAdminIndexResult;
  reload?: () => void;
}

export default (props: PropsWithChildren<Props>) => {
  const { data, reload, children } = props;

  const [form] = Form.useForm<FormData>();

  return (
    <ModalForm
      layout="horizontal"
      width={400}
      labelCol={{style: {width: 100}}}
      modalProps={{
        maskClosable: false,
      }}
      form={form}
      onOpenChange={(val) => {
        if (val) {
          if (data?.uuid) {
            form.setFieldsValue({
              ...data,
              imgs: data.img ? [data.img]: undefined,
            });
          }
        } else {
          form.resetFields();
        }
      }}
      title={data?.uuid ? '品牌编辑' : '添加品牌'}
      trigger={children as JSX.Element}
      onFinish={(values) => {
        let service;
        const {imgs, ...restValues} = values;
        const newValues: API.BrandAdminCreateDto = {
          ...restValues,
          img: imgs?.[0],
        };
        if (data?.uuid) {
          service = brandV1AdminControllerUpdate({uuid: data.uuid},newValues);
        } else {
          service = brandV1AdminControllerCreate(newValues);
        }
        return service
          .then(() => {
            message.success('操作成功');
            reload?.();
            return true;
          })
          .catch(() => {
            return false;
          });
      }}
    >
      <Form.Item
        name="imgs"
        label="logo"
      >
        <FileUpload max={1} fileGroup={FileGroup.BRAND} />
      </Form.Item>
      <ProFormText
        name="title"
        label="标题"
        rules={[{ required: true, message: '请输入' }]}
        fieldProps={{
          maxLength: 200,
        }}
      />
      <ProFormTextArea
        name="desc"
        label="描述"
        fieldProps={{
          maxLength: 500,
          showCount: true,
        }}
      />
    </ModalForm>
  );
};
